package com.heima.page.service;

import com.alibaba.fastjson.JSON;
import com.heima.common.exception.config.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
@Slf4j
public class GeneratePageService {


    @Autowired
    Configuration configuration;

    @Autowired
    ArticleFeign articleFeign;

    @Resource(name = "minIOFileStorageService")
    FileStorageService fileStorageService;


    /**
     * 生成静态页面逻辑
     * @param articleId
     * @throws Exception
     */
    public void generateArticlePage(Long articleId) throws Exception {

        //1 模板
        Template template = configuration.getTemplate("article.ftl", "UTF-8");

        //2 数据
        // 文章内容和文章基本数据
        ApArticleContent articleContent = articleFeign.findArticleContentById(articleId);
        if (articleContent == null || StringUtils.isBlank(articleContent.getContent())) {
            CustException.cust("文章内容为空 articleId：" + articleId);
        }
        ApArticle article = articleFeign.findArticleById(articleId);

        Map map = new HashMap();
        map.put("article", article);

        String content = articleContent.getContent();  // 集合字符串
        List<Map> contentList = JSON.parseArray(content, Map.class);
        map.put("content", contentList);


        //***** authorApUserId
        ApAuthor author = articleFeign.findApAuthorById(article.getAuthorId());
        if (author == null || author.getUserId() == null) {
            CustException.cust("文章作者不能为空 authorId：" + article.getAuthorId());
        }
        Integer authorApUserId = author.getUserId();
        map.put("authorApUserId", authorApUserId);


        //3 生成静态页面
        StringWriter out = new StringWriter();
        template.process(map, out);
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());

        //4 需要将静态页面上传到MinIO中
        String fileUrl = fileStorageService.store("article", articleId + ".html","text/html", is);
        //5 更新Article数据，添加静态文件的url
        if (StringUtils.isBlank(fileUrl)) {
            CustException.cust("上传文件到MinIO失败 articleId：" + articleId);
        }
        article.setStaticUrl(fileUrl);
        articleFeign.updateArticleById(article);
    }

}
